#include "addfriendsender.h"
#include "ui_addfriendsender.h"
#include "user.h"
#include "maininterfacewidget.h"
#include <QHostAddress>
#include <QMessageBox>
addfriendsender::addfriendsender(QWidget *parent,user userSelf) :
    QDialog(parent),
    ui(new Ui::addfriendsender)
{
    ui->setupUi(this);
    //connect()
    qDebug() << "userSelf:" << userSelf.getUserName();
    //websocket传输代码
    this->userSelf = userSelf;
    socket = new QWebSocket();//新建websocket
    QUrl url("ws://101.43.168.188:19999/slimarveous/ws");
    QUrlQuery query;//在query里面添加id token两个信息
    query.addQueryItem("id",userSelf.getUserId());
    query.addQueryItem("token",userSelf.getUserPassword());
    url.setQuery(query);
    socket->open(url);
    //连接到server
    QObject::connect(socket, &QWebSocket::connected,[=]() {
        qDebug() << "WebSocket connected";
    });
    //断开链接
    QObject::connect(socket, &QWebSocket::disconnected, [=]() {
        qDebug() << "WebSocket disconnected";
    });
    //获取信息
}
void addfriendsender::on_btn_send_addfriendsender_clicked()
{
    //Sender创建
    UserBrief Sender;
    Sender = {
        userSelf.getUserId(),//id
        userSelf.getUserName(),//username
        "",//photo
        userSelf.getUserGender()//gender
    };
//    qDebug() << "sender信息:" << Sender.username + Sender.id;
    //get content
    QString Brief = ui->messageSendTextEdit->toPlainText();//传输服务器
    QString senderToken = ui->senderToken->text();
    QString receiverId = ui->receiverId->text();
    receiverId.toLongLong();//id转化为long long
    //connect to server

    //sender信息
    QJsonObject senderValue{
        {"id", Sender.id.toInt()},
        {"username", Sender.username},
        {"photo", ""},
        {"gender", Sender.gender.toInt()}
    };
    //发送的信息
    QJsonObject json{
        {"Token",senderToken},
        {"sender",senderValue},
        {"ReceiverId",receiverId},
        {"Brief", Brief}
    };

    QJsonDocument doc(json);

    QByteArray data = doc.toJson(QJsonDocument::Compact);
    //qDebug() << "doc:" << doc << "data:" << data;

    socket->sendTextMessage(data);
    //ui->dialogTextBrowser->append("me: "+ sendContent);
    ui->messageSendTextEdit->clear();
    this->close();
    QMessageBox:: information(this, "好友请求","你好，"+userSelf.getUserName()+"! "+"你已向用户id为：" +receiverId+"的好友发送请求！");
 //跳转到主界面
    MainInterfaceWidget* mainWindow = new MainInterfaceWidget(nullptr, userSelf);
    mainWindow->show();
}


void addfriendsender::on_btn_clear_addfriendsender_clicked()
{
    ui->messageSendTextEdit->clear();
    ui->receiverId->clear();
}


addfriendsender::~addfriendsender()
{
    delete ui;
}
